#pragma once
#include <iostream>
#include <cstring>
#include <cstdlib>


class Thread
{
public:
    typedef enum{
        NEW=0,
        RUNNING,
        EXITED
    }ThreadStat;
    typedef void(*func_t)(void*);
public:
    Thread(int num,func_t func,void * args)
    :_func(func),_args(args),_stat(0),_tid(0)
    {
        char name[64];
        snprintf(name,sizeof(name),"thread-%d",num);
        _name=name;
    }

    ~Thread()
    {}

    int status()
    {
        return _stat;
    }
    std::string threadname()
    {
        return _name;
    }
    pthread_t threadid()
    {
        if(_stat=-RUNNING) return _tid;
        else return 0;
    }
    static void * runHelper(void * args)
    {
        Thread* t=(Thread*) args;
        (*t)();
        return nullptr;
    }
    void operator()()
    {
        if(_func) _func(_args);
    }
    void run()
    {
       int n=pthread_create(&_tid,nullptr,runHelper,this);
    }
    void join()
    {
        int n=pthread_join(_tid,nullptr);
        if(n != 0)
        {
            std::cerr<<"join error"<<strerror(errno)<<std::endl;
            return ;
        }
        _stat=EXITED;
    }

private:
    pthread_t _tid;
    func_t _func;
    void * _args;
    int _stat;
    std::string _name;

};